package com.pinyoumei.app.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pinyoumei.app.R;
import com.pinyoumei.app.bean.BaseBean;
import com.pinyoumei.app.bean.SettingUserBean;
import com.pinyoumei.app.bean.UploadFileResponse;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.EventBusUtils;
import com.pinyoumei.app.utils.IntentUtils;
import com.pinyoumei.app.utils.PermissionUtils;
import com.pinyoumei.app.utils.PhotoUtils;
import com.pinyoumei.app.utils.PicUtils;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.ToastUtils;
import com.pinyoumei.app.utils.event.ReshEvent;
import com.pinyoumei.app.utils.event.WxLoginEvent;
import com.pinyoumei.app.view.PhotoSelectDialog;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by Administrator on 2021-08-14.
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2021-08-14        Administrator             新增Person类
 * 2021-08-14        Administrator             增加sex属性
 * 个人资料
 */
public class UserInfoActivity extends BaseActivity implements View.OnClickListener {

    private PhotoSelectDialog dialog;
    private String imagePath;//图片保存路径
    private Uri cropImageUri;
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.jpg");
    private String actionUrl = Constants.MAIN_URL + "app/uploadImg";//上传图片的服务器地址

    private String newName = "image.jpg";
    private String mPic;
    private String picUrl = "";//服务器返回图片的url
    private static final int output_X = 600;
    private static final int output_Y = 600;
    private FileInputStream fStream;//文件流
    private static final int CODE_RESULT_REQUEST = 0xa2;

    private CircleImageView mIvHeadImg;
    private TextView mTvNickName;
    private TextView mTvPhone;
    private TextView mTvWechat;
    private TextView mTvCode;
    private TextView mTvTime;
    private TextView mTvUserRealName;
    private TextView mTvIdcard;
    private TextView mTvAli;
    private String user_nick_name = "";
    private String user_head_img = "";


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        EventBusUtils.register(this);
        InitWidget();

        InitData();
    }



    private void InitWidget() {


        ImageView iv_close = findViewById(R.id.iv_close);
        iv_close.setOnClickListener(this);
        RelativeLayout mRlHeadImg = findViewById(R.id.rl_head_img);
        mRlHeadImg.setOnClickListener(this);
        RelativeLayout  mRlNickName = findViewById(R.id.rl_nick_name);
        mRlNickName.setOnClickListener(this);
        RelativeLayout  mRlBindPhone = findViewById(R.id.rl_bind_phone);
        mRlBindPhone.setOnClickListener(this);
        RelativeLayout  mRlWechatBind = findViewById(R.id.rl_wechat_bind);
        mRlWechatBind.setOnClickListener(this);
        RelativeLayout mRlAli = findViewById(R.id.rl_ali);
        mRlAli.setOnClickListener(this);


        mIvHeadImg = findViewById(R.id.iv_head_img);

        mTvNickName = findViewById(R.id.tv_nick_name);

        mTvPhone = findViewById(R.id.tv_phone);

        mTvWechat = findViewById(R.id.tv_wechat);
        mTvCode = findViewById(R.id.tv_code);
        mTvTime = findViewById(R.id.tv_time);
        mTvUserRealName = findViewById(R.id.tv_user_real_name);
        mTvIdcard = findViewById(R.id.tv_idcard);

        mTvAli = findViewById(R.id.tv_ali);

        dialog = new PhotoSelectDialog(UserInfoActivity.this, R.layout.item_layout_photoselect, new int[]{});
        dialog.setOnClickListener(new PhotoSelectDialog.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.relative_photo://进入相机
                        Intent intent_photo = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(intent_photo, 1);
                        break;
                    case R.id.relative_native://进入本地相册
                        Intent intent_native = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intent_native, 2);
                        break;
                }
            }
        });
    }




    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMessageEventMain(WxLoginEvent event) {
        if (!TextUtils.isEmpty(event.openid)) {

            BandWechat(event.openid,event.user_nick_name,event.user_head_img);
            EventBusUtils.removeStickyEvent(WxLoginEvent.class);
        }

    }


    @Subscribe(threadMode = ThreadMode.MAIN, priority = 1)
    public void onMessageEventMain(ReshEvent event) {
        if (event != null ) {

            InitData();
        }
    }
    private void InitData() {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(UserInfoActivity.this));

        OkGo.<String>post(Constants.SETTING_USERINFO)
                .params("user_id", SPUtils.getAppUserId(UserInfoActivity.this))
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }


                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);

                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();

                        SettingUserBean settingUserBean = gson.fromJson(response.body(), SettingUserBean.class);

                        if (settingUserBean.getCode() >= 0) {
                            user_head_img = settingUserBean.getResult().getData_info().getUser_head_img();
                             user_nick_name =settingUserBean.getResult().getData_info().getUser_nick_name();


                            Glide.with(UserInfoActivity.this).load(user_head_img).into(mIvHeadImg);
                            mTvNickName.setText(user_nick_name);
                            mTvPhone.setText(settingUserBean.getResult().getData_info().getUser_phone());
                            mTvWechat.setText(settingUserBean.getResult().getData_info().getIs_bind_wx());
                            mTvCode.setText(settingUserBean.getResult().getData_info().getRecommand_code());
                            mTvTime.setText(settingUserBean.getResult().getData_info().getRegister_time());
                            mTvUserRealName.setText(settingUserBean.getResult().getData_info().getUser_real_name());
                            mTvIdcard.setText(settingUserBean.getResult().getData_info().getUser_id_no());
                            mTvAli.setText(settingUserBean.getResult().getData_info().getUser_alipay_account());

                        } else {
                            ToastUtils.showShort(settingUserBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }
                });


    }


    private void SendHeadData(String url) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(UserInfoActivity.this));
        map.put("user_head_img", url);

        OkGo.<String>post(Constants.SETTING_UPDATEIMG)
                .params("user_id", SPUtils.getAppUserId(UserInfoActivity.this))
                .params("user_head_img", url)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }


                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);

                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();

                        BaseBean settingUserBean = gson.fromJson(response.body(), BaseBean.class);

                        if (settingUserBean.getCode() >= 0) {
                            ToastUtils.showShort(settingUserBean.getMsg());
                        } else {
                            ToastUtils.showShort(settingUserBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }
                });


    }



    private void BandWechat(String open_id,String user_nick_name,String user_head_img) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(UserInfoActivity.this));
        map.put("open_id", open_id);
        map.put("user_nick_name", user_nick_name);
        map.put("user_head_img", user_head_img);

        OkGo.<String>post(Constants.SETTING_WECHAT_BAND)
                .params("user_id", SPUtils.getAppUserId(UserInfoActivity.this))
                .params("open_id", open_id)
                .params("user_nick_name", user_nick_name)
                .params("user_head_img", user_head_img)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }


                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);

                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();

                        BaseBean settingUserBean = gson.fromJson(response.body(), BaseBean.class);

                        if (settingUserBean.getCode() >= 0) {
                            InitData();
                            ToastUtils.showShort(settingUserBean.getMsg());
                        } else {
                            ToastUtils.showShort(settingUserBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }
                });


    }
    //上传图片请求
    private void uploadPic(Bitmap bitmap) {
        // 上传至服务器
        // ... 可以在这里把Bitmap转换成file，然后得到file的url，做文件上传操作
        //先将图片保存到本地
        imagePath = PicUtils.savePhoto(bitmap, Environment
                .getExternalStorageDirectory().getAbsolutePath(), String
                .valueOf(System.currentTimeMillis()));
        if (imagePath != null) {
            // 拿着imagePath上传了
            // ...
            Thread thread = new Thread(runnable);
            thread.start();
        }
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            Looper.prepare();// 创建消息循环
            uploadFile();
            Message msg = new Message();
//          data.putString("image",  fStream);
            handler.sendMessage(msg);
            Looper.loop();// 从消息队列取消
        }
    };
    Handler handler = new Handler() {

        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    //上传用户图片
                    SendHeadData(picUrl);
                    break;
            }
        }


    };

    /* 上传文件至Server的方法 */
    private void uploadFile() {
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        try {
            URL url = new URL(actionUrl);//服务器地址
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            /* 允许Input、Output，不使用Cache */
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            /* 设置传送的method=POST */
            con.setRequestMethod("POST");
            /* setRequestProperty *///设置请求属性
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setRequestProperty("Charset", "UTF-8");
            con.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            /* 设置DataOutputStream *///数据输出流
            //heading为服务器接收的键
            DataOutputStream ds = new DataOutputStream(con.getOutputStream());
            ds.writeBytes(twoHyphens + boundary + end);
            ds.writeBytes("Content-Disposition: form-data; " + "name=\"uppic\";filename=\"" + newName + "\"" + end);
            ds.writeBytes(end);
            /* 取得文件的FileInputStream */ //文件输入流
            fStream = new FileInputStream(imagePath);//要上传的图片路径，
            /* 设置每次写入1024bytes */
            int bufferSize = 10240;
            byte[] buffer = new byte[bufferSize];
            int length = -1;
            /* 从文件读取数据至缓冲区 */
            while ((length = fStream.read(buffer)) != -1) {
                /* 将资料写入DataOutputStream中 */
                ds.write(buffer, 0, length);
            }
            ds.writeBytes(end);
            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
            /* close streams */
            fStream.close();
            ds.flush();
            /* 取得Response内容 */
            InputStream is = con.getInputStream();
            int ch;
            StringBuffer b = new StringBuffer();
            while ((ch = is.read()) != -1) {
                b.append((char) ch);
            }
            mPic = b.toString().trim();
            Gson gson = new Gson();
            UploadFileResponse uploadFileResponse = gson.fromJson(mPic, UploadFileResponse.class);
            picUrl = uploadFileResponse.getResult().getImg_url();
            ds.close();
            //上传图片提交
            handler.sendEmptyMessage(1);
        } catch (Exception e) {
            Toast.makeText(UserInfoActivity.this, "图片上传失败", Toast.LENGTH_SHORT).show();
            
        }
    }


    //进入相机或者相册后的回调
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) {//避免进入相机不拍照直接返回的时候空指针异常
            return;
        }
        switch (requestCode) {
            case 1://相机拍照的回调
                if (requestCode == 1) {
                    cropImageUri = Uri.fromFile(fileCropUri);
                    Bundle bundle = data.getExtras();
                    Bitmap bitmap_photo = (Bitmap) bundle.get("data");
                    Uri uri_photo = Uri.parse(MediaStore.Images.Media.insertImage(this.getContentResolver(), bitmap_photo, null, null));
                    Glide.with(this).load(uri_photo).into(mIvHeadImg);
                    //对图片进行裁剪
                    PhotoUtils.cropImageUri(this, uri_photo, cropImageUri, 1, 1, output_X, output_Y, CODE_RESULT_REQUEST);
                }
                break;
            case 2://相册选择的回调
                if (requestCode == 2) {
                    cropImageUri = Uri.fromFile(fileCropUri);
                    Uri uri_native = data.getData();
                    Bitmap bitmap_native = PhotoUtils.getBitmapFromUri(uri_native, this);
                    Glide.with(this).load(uri_native).into(mIvHeadImg);
                    //对图片进行裁剪
                    PhotoUtils.cropImageUri(this, uri_native, cropImageUri, 1, 1, output_X, output_Y, CODE_RESULT_REQUEST);
                }
                break;
            case CODE_RESULT_REQUEST://图片裁剪完成的回调
                Bitmap bitmap = PhotoUtils.getBitmapFromUri(cropImageUri, this);
                if (bitmap != null) {
                    uploadPic(bitmap);//上传图片至服务器
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBusUtils.unregister(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        	case R.id.iv_close:
                finish();
        		break;
case R.id.rl_head_img:
                //先检测相机权限跟SD卡访问权限
                PermissionUtils.checkAndRequestMorePermissions(UserInfoActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 22, new PermissionUtils.PermissionRequestSuccessCallBack() {
                    @Override
                    public void onHasPermission() {//用户已授予权限
                        dialog.show();
                    }
                });
        		break;

        		case R.id.rl_nick_name:
                startActivity(new Intent(UserInfoActivity.this,ChangeNicknNmeActivity.class));
        		break;
        	case R.id.rl_bind_phone:
                startActivity(new Intent(UserInfoActivity.this,ChangePhoneActivity.class));

        		break;
        	case R.id.rl_wechat_bind:
        	    if (mTvWechat.getText().toString().equals("未绑定")){
                    IntentUtils.loginWeixin(UserInfoActivity.this,"wxfcdbc78aac617cee");
                }
        		break;
	case R.id.rl_ali:
        startActivity(new Intent(UserInfoActivity.this,AliPayPasswordActivity.class));

        break;

        	default:
        		break;
        }
    }
}
